package com.tinymce.imageupload;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/editor")
@CrossOrigin(origins = "*", methods = {GET, POST}, allowedHeaders = "*", maxAge = 3600)
public class FileUploadController {


    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    private final FileUploadService fileUploadService;
    //图片最大上传限制2M
    private final int IMG_MAX_SIZE=2;
    //视频最大上传限制10M
    private final int VIDEO_MAX_SIZE=10;
    //文件最大上传限制10M
    private final int FILE_MAX_SIZE=10;


    @Autowired
    public FileUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }
    @PostMapping("uploadImage")
    public Map<String, String> uploadImage(MultipartFile file, HttpServletRequest request){
        // 允许上传的文件类型
        HashMap<String, String> mFileTypes = new HashMap<String, String>();
        mFileTypes.put("image/jpeg","jpg");
        mFileTypes.put("image/png","png");
        mFileTypes.put("image/bmp","bmp");
        mFileTypes.put("image/gif","gif");


        String type = file.getContentType();
        String fileType=mFileTypes.get(type);


        logger.info("文件上传类型：{}", type);
        Map<String, String> map = new HashMap<>();
        if(fileType==null){
            map.put("stat", "0");
            map.put("msg", "上传文件格式不被允许");
            map.put("location", "");
            return map;
        }
        if(!checkFileSize( file.getSize(),IMG_MAX_SIZE,"M")){
            map.put("stat", "0");
            map.put("msg", "上传图片文件应不大于 "+IMG_MAX_SIZE+" M");
            map.put("location", "");
            return map;
        }

        String path = request.getSession().getServletContext().getRealPath("upload");
        logger.info("文件存储路径：{}", path);
        map = fileUploadService.upload(file, path,fileType);

        System.out.println(map);

        return map;
    }
    @PostMapping("uploadVideo")
    public Map<String, String> uploadVideo(MultipartFile file, HttpServletRequest request){
        // 允许上传的文件类型
        HashMap<String, String> mFileTypes = new HashMap<String, String>();
        mFileTypes.put("video/mp4","mp4");
        mFileTypes.put("audio/mpeg","mp3");

        String type = file.getContentType();
        String fileType=mFileTypes.get(type);
        logger.info("文件上传类型：{}", type);
        Map<String, String> map = new HashMap<>();
        if(fileType==null){
            map.put("stat", "0");
            map.put("msg", "上传文件格式不被允许");
            map.put("location", "");
            return map;
        }
        if(!checkFileSize( file.getSize(),VIDEO_MAX_SIZE,"M")){
            map.put("stat", "0");
            map.put("msg", "上传文件应不大于 "+VIDEO_MAX_SIZE+" M");
            map.put("location", "");
            return map;

        }

        String path = request.getSession().getServletContext().getRealPath("upload");
        logger.info("文件存储路径：{}", path);
        map = fileUploadService.upload(file, path,fileType);
        System.out.println(map);

        return map;
    }
    @PostMapping("uploadFile")
    public Map<String, String> uploadFile(MultipartFile file, HttpServletRequest request) {
        // 这个路径 path 就是工程下 /src/main/webapp/upload，这个路径是发布后才会存在
        // 本地运行会创建在其他目录下，如 C:\\Users\\userName\\AppData\Local\\Temp\\tomcat-docbase.141614960009226192.9090\\upload
        // 允许上传的文件类型
        Map<String, String> mFileTypes = new HashMap<String, String>();
        mFileTypes.put("image/jpeg","jpg");
        mFileTypes.put("image/png","png");
        mFileTypes.put("image/bmp","bmp");
        mFileTypes.put("image/gif","gif");
        mFileTypes.put("application/pdf","pdf");
        mFileTypes.put("application/zip","zip");
        mFileTypes.put("application/octet-stream","rar");
        mFileTypes.put("application/vnd.ms-excel","xls");
        mFileTypes.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlsx");
        mFileTypes.put("application/msword","doc");
        mFileTypes.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document","docx");
        mFileTypes.put("application/vnd.ms-powerpoint","ppt");
        mFileTypes.put("application/vnd.openxmlformats-officedocument.presentationml.presentation","pptx");

        String type = file.getContentType();
        String fileType=mFileTypes.get(type);
        logger.info("文件上传类型：{}", type);



        Map<String, String> map = new HashMap<String, String>();
        if(fileType==null){
            map.put("stat", "0");
            map.put("msg", "上传文件格式不被允许");
            map.put("location", "");
            return map;
        }
        if(!checkFileSize( file.getSize(),FILE_MAX_SIZE,"M")){
            map.put("stat", "0");
            map.put("msg", "上传文件应不大于 "+FILE_MAX_SIZE+" M");
            map.put("location", "");
            return map;

        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        logger.info("文件存储路径：{}", path);

        //增加后缀名判断
        String filename = file.getOriginalFilename();
        // 获取文件扩展名，如 abc.de.jpg，就获取 jpg
        String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
        //上传附件使用后缀名
        String[] strArr = new String[] { "jpg", "jpeg","png","gif","zip","rar","doc","docx","xls","xlsx","ppt","pptx","pdf"};
        List<String> list = Arrays.asList(strArr);
        boolean result = list.contains(extensionName);
        if(!result){
            map.put("stat", "0");
            map.put("msg", "上传文件格式不被允许");
            map.put("location", "");
            return map;
        }

        map = fileUploadService.upload(file, path,extensionName);

        //map = fileUploadService.upload(file, path,fileType);
        System.out.println(map);

        /*
        Map<String, String> map = new HashMap<>();
        if(imageUrl==null){
            map.put("location", null);
            map.put("msg", "上传失败");
        }else{
            map.put("location", IMAGE_URL_PREFIX + imageUrl);
        }
        */

        //  TinyMCE 要求图片上传后，需要返回一个 json 对象，这个对象必须有 location 属性，此处硬编码


        return map;
    }

    @PostMapping("/upload-content")
    public String uploadContent(@RequestBody String content) {
        logger.info("method: uploadContent，上传内容：{}", content);
        // TODO 直接将这部分内容存储到数据库即可，此时 content里的图片已经不是 base64
        return content;
    }
    /**
     * 判断文件大小
     *
     * @param len
     *            文件长度
     * @param size
     *            限制大小
     * @param unit
     *            限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
}
